package com.yueqian.framework.limiter;

import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;


public class SlidingWindowRateLimiter {

	public boolean allowRequest(String key) {
		// 当前时间戳
		long currentTime = System.currentTimeMillis();

		// 使用Lua脚本来确保原子性操作
		String luaScript = "local window_start = tonumber(ARGV[1]) - 60000\n" +
								   "redis.call('ZREMRANGEBYSCORE', KEYS[1], '-inf', window_start)\n" +
								   "local current_requests = redis.call('ZCARD', KEYS[1])\n" +
								   "if current_requests < tonumber(ARGV[2]) then\n" +
								   "    local unique_member = redis.call('INCR', 'unique_member_key')\n" +
								   "    redis.call('ZADD', KEYS[1], ARGV[1], unique_member)\n" +
								   "    return 1\n" +
								   "else\n" +
								   "    return 0\n" +
								   "end";

		Jedis jedis = new Jedis();
		int limit = 10;
		Object result = jedis.eval(luaScript, 1, key, String.valueOf(currentTime), String.valueOf(limit));
		return (Long) result == 1;
	}
}
